﻿using AcexeService.Models;
using AcexeService.ServiceModel.Basic;
using ServiceStack;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Linq;

//https://github.com/ServiceStack/ServiceStack.OrmLite
namespace AcexeService.ServiceInterface
{
    [Authenticate]
    public class SysEmployeeServices : Service
    {
        /// <summary>
        /// 通过员工ID(EmployeeId)取员工实体数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(GetEmployee request)
        {
            var list = Db.Select<BSC_EMPLOYEE>(c => c.EMPID == request.EmployeeId);
            if (list.Count > 0)
            {
                return list[0];
            }
            return null;
        }

        /// <summary>
        /// 查询员工数据（分页、导出）
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(GetEmployeeList request)
        {

            var miniuigridmodel = new MiniUiGridModel<BSC_EMPLOYEE>();
            var model = request.BscEmpModel;

            var q = Db.From<BSC_EMPLOYEE>();

            q.And(x => x.ISDELETED == model.ISDELETED);

            if (!string.IsNullOrEmpty(request.FuzzyEmployeeName))
                q.And(p => p.EMPNAME.Contains(request.FuzzyEmployeeName));

            miniuigridmodel.total = Db.Scalar<int>(q.Select(Sql.Count("*")));

            if (!request.Page.IsGetWholeData)
            {
                q.Take(request.Page.PageSize);
                q.Skip(request.Page.PageSize * request.Page.PageIndex);
            }

            if (!string.IsNullOrEmpty(request.Page.SortField))
            {
                if (request.Page.SortOrder == "asc")
                    q.OrderByFields(request.Page.SortField);
                else
                    q.OrderByFieldsDescending(request.Page.SortField);
            }
            else
            {
                q.OrderBy(x => x.EMPNO);
            }

            miniuigridmodel.data = Db.Select<BSC_EMPLOYEE>(q.Select(c => c));

            return miniuigridmodel;

        }

        /// <summary>
        /// 新增员工
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(AddEmployee request)
        {
            var dto = new MessageDto();
            var model = request.BscEmpModel;

            if (string.IsNullOrEmpty(model.EMPID))
            {
                dto.Flag = false;
                dto.Msg = "员工ID不允许为空";
                return dto;
            }
            if (string.Equals(model.EMPNO, ""))
            {
                dto.Flag = false;
                dto.Msg = "员工编号不允许为空";
                return dto;
            }
            // 字段值为null时不会更新数据，但是为""会更新为""
            if (string.Equals(model.EMPNAME, ""))
            {
                dto.Flag = false;
                dto.Msg = "员工姓名不允许为空";
                return dto;
            }

            try
            {
                Db.Insert<BSC_EMPLOYEE>(model);
                dto.Flag = true;
                dto.Msg = "新增成功";
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }

        /// <summary>
        /// 编辑员工
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(EditEmployee request)
        {
            var dto = new MessageDto();
            var model = request.BscEmpModel;

            if (string.IsNullOrEmpty(model.EMPID))
            {
                dto.Flag = false;
                dto.Msg = "员工ID不允许为空";
                return dto;
            }
            if (string.Equals(model.EMPNO, ""))
            {
                dto.Flag = false;
                dto.Msg = "员工编号不允许为空";
                return dto;
            }
            // 字段值为null时不会更新数据，但是为""会更新为""
            if (string.Equals(model.EMPNAME, ""))
            {
                dto.Flag = false;
                dto.Msg = "员工姓名不允许为空";
                return dto;
            }

            try
            {
                var list = Db.Select<BSC_EMPLOYEE>(c => c.EMPID == model.EMPID);
                if (list.Count == 0)
                {
                    dto.Flag = false;
                    dto.Msg = "您编辑的员工不存在，请刷新页面后重试";
                    return dto;
                }

                var editmodel = list[0];

                // 是否需要修改用户表的 ISDELETED，ISVALID 字段
                var isNeedUpdateSysUser = editmodel.ISDELETED != model.ISDELETED;


                using (System.Data.IDbTransaction dbTrans = Db.OpenTransaction())
                {

                    if (isNeedUpdateSysUser && !string.IsNullOrEmpty(editmodel.EMPUSERID))
                    {
                        string userid = editmodel.EMPUSERID;
                        Db.Update<SYS_USER>(new { ISVALID = !model.ISDELETED, ISDELETED = model.ISDELETED }, p => p.USERID == userid);
                    }

                    editmodel = AcexeService.ServiceInterface.Lib.AutoTransfer.GetModel<BSC_EMPLOYEE>(editmodel, model);
                    Db.Update<BSC_EMPLOYEE>(editmodel);


                    dbTrans.Commit();
                }
                dto.Flag = true;
                dto.Msg = "修改成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }

        /// <summary>
        /// 删除员工
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(DeleteEmployee request)
        {
            var dto = new MessageDto();

            if (request.EmployeeId.Equals(string.Empty))
            {
                dto.Flag = false;
                dto.Msg = "空记录";
                return dto;
            }

            try
            {
                //只作虚删除
                using (System.Data.IDbTransaction dbTrans = Db.OpenTransaction())
                {
                    var model = Db.Single<BSC_EMPLOYEE>(p => p.EMPID == request.EmployeeId);
                    Db.Update<BSC_EMPLOYEE>(new { ISDELETED = true, UPDATEON = DateTime.Now, UPDATEBY = request.DeleteBy }, p => p.EMPID == request.EmployeeId);
                    if (!string.IsNullOrEmpty(model.EMPUSERID))
                    {
                        Db.Update<SYS_USER>(new { ISVALID = false, ISDELETED = true, UPDATEON = DateTime.Now, UPDATEBY = request.DeleteBy }, p => p.USERID == model.EMPUSERID);
                    }

                    dbTrans.Commit();
                }

                dto.Flag = true;
                dto.Msg = "注销成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
                return dto;
            }
        }
    }

}